package com.ruoyi.order.controller;

import cn.hutool.poi.excel.ExcelReader;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.order.domain.SysOrder;
import com.ruoyi.order.domain.SysProd;
import com.ruoyi.order.mapper.SysOrderMapper;
import com.ruoyi.order.service.ISysOrderService;
import com.ruoyi.order.service.ISysProdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 订单记录Controller
 *
 * @author yj
 * @date 2023-11-14
 */
@RestController
@RequestMapping("/system/order")
public class SysOrderController extends BaseController {
    @Autowired
    private ISysOrderService sysOrderService;
    @Resource
    private SysOrderMapper sysOrderMapper;

    @Autowired
    private ISysProdService sysProdService;

    /**
     * 查询订单记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/list")
//    public TableDataInfo list(SysOrder sysOrder,Integer receiptType) {
    public TableDataInfo list(SysOrder sysOrder) {
        startPage();
        List<SysOrder> list = sysOrderService.selectSysOrderList(sysOrder);
        list.forEach(item -> {
            item.setSysProdList(sysOrderService.selectSysOrderById(item.getId()).getSysProdList());
        });
        return getDataTable(list);
    }

    /**
     * 称重收货管理：查询未收货订单下的货物
     * @param sysOrder
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/noReceiptList")
    public TableDataInfo noReceiptList(SysOrder sysOrder) {
        startPage();
        List<SysOrder> list = sysOrderService.selectSysOrderList(sysOrder);
        list.forEach(item -> {
            try {
                List<SysProd> sysProdList = sysOrderService.noReceiptList(item.getId()).getSysProdList();
                if (sysProdList != null) {
                    item.setSysProdList(sysProdList);
                }
                item.setSysProdList(sysProdList);
            } catch (NullPointerException e) {
                // 处理空指针异常，例如输出错误日志或进行其他逻辑处理
                System.out.println("Error: NullPointerException occurred.");
                System.out.println("订单下没有未收货的物品.");
            }
        });

        //foreach 遍历完后list包含sysProdList为null的元素，使用Iterator来过滤
        Iterator<SysOrder> iterator = list.iterator();
        while (iterator.hasNext()) {
            SysOrder item = iterator.next();
            if(item.getSysProdList() == null){
                iterator.remove();
            }
        }
        //此处分页只能放在最后，放在前面分页 list没有进行过滤 总条数 不正确
        startPage();
        return getDataTable(list);
    }

    /**
     * 导出订单记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:export')")
    @Log(title = "订单记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response) {
        List<SysOrder> list = sysOrderService.getOrderAndProd();
        ExcelUtil<SysOrder> util = new ExcelUtil<SysOrder>(SysOrder.class);
        util.exportExcel(response, list, "订单详情","订单详情");
    }

    /**
     * 获取订单记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
//        return success(sysOrderService.selectSysOrderById(id,null));
        return success(sysOrderService.selectSysOrderById(id));
    }


    /**
     * 新增订单记录
     */
    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "订单记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysOrder sysOrder) {
        if (sysOrderMapper.selectSysOrderByOrderCode(sysOrder.getOrderCode()) != 0) {
            return AjaxResult.error("编码重复");
        }
        return toAjax(sysOrderService.insertSysOrder(sysOrder));
    }


    @Log(title = "订单记录", businessType = BusinessType.INSERT)
    @PostMapping("addProd")
    public AjaxResult addProd(@RequestBody SysProd sysProd) {
        return toAjax(sysOrderService.insertSysProd(sysProd));
    }

    /**
     * 订单记录 导入模板
     * @param response
     */
    @PostMapping("/importOrderTemplate")
    public void importTemplate(HttpServletResponse response)
    {
//        ExcelUtil<SysOrder> util = new ExcelUtil<SysOrder>(SysOrder.class);
        ExcelUtil<SysProd> util1 = new ExcelUtil<SysProd>(SysProd.class);

//        util.importTemplateExcel(response, "订单记录");
        util1.importTemplateExcel(response, "物品信息");
    }


    @PreAuthorize("@ss.hasPermi('system:order:importOrder')")
    @PostMapping("importOrder")
    public AjaxResult importOrder(MultipartFile file) {
        List<SysOrder> orderList;
        List<SysProd> prodList;
        try {
            ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(file.getInputStream());

            HashMap<String, String> orderMap = new HashMap<>();
            orderMap.put("订单编号", "orderCode");
            orderMap.put("订单签订时间", "orderTime");

            reader.setHeaderAlias(orderMap);
            reader.setSheet(0);
            orderList = reader.readAll(SysOrder.class);
            List<SysOrder> sysOrders = orderList.stream().distinct().collect(Collectors.toList());
            Flux.fromIterable(sysOrders).subscribe(sysOrderService::insertSysOrder);


            if (CollectionUtils.isEmpty(sysOrders)) {
                return AjaxResult.error("文档中没有数据");
            }

            ExcelReader prodReader = cn.hutool.poi.excel.ExcelUtil.getReader(file.getInputStream());
            HashMap<String, String> prodMap = new HashMap<>();
            prodMap.put("订单编号", "orderCode");
            prodMap.put("货物编码", "prodCode");
            prodMap.put("货物名称", "prodName");
            prodMap.put("订购数量", "quantity");
            prodMap.put("物品单位", "prodUnits");
            prodMap.put("物品单价", "prodPrice");
            prodMap.put("预定时间", "scheduledTime");
            prodMap.put("实到数量", "actualQuantity");
            prodMap.put("去皮数量", "decorticateQuantity");
            prodReader.setHeaderAlias(prodMap);
            prodReader.setSheet(0);
            prodList = prodReader.readAll(SysProd.class);


            Flux.fromIterable(prodList).subscribe(sysOrderService::insertSysProd);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
            return AjaxResult.success();
    }

    /**
     * 修改订单记录
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "订单记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysOrder sysOrder) {
        return toAjax(sysOrderService.updateSysOrder(sysOrder));
    }

    /**
     * 删除订单记录
     */
    @PreAuthorize("@ss.hasPermi('system:order:remove')")
    @Log(title = "订单记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysOrderService.deleteSysOrderByIds(ids));
    }

}
